package router

import (
	"back/conf"
	"back/conf/global"
	"back/initx"
	"back/router/middle"
	nail "back/router/router"
	"back/static"
	"fmt"
	"github.com/gin-contrib/gzip"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"utilx/logx"
)

func Router() {
	//=====加载配置文件==
	initConf := initx.InitConf()
	initx.InitDB(initConf)
	initx.InitDBModel(global.DB)
	//========
	if !initConf.Debug {
		gin.SetMode(gin.ReleaseMode)
	}
	//===
	engine := gin.Default() // ROOT: /
	engine.Use(middle.Cros())

	// NoRoute 非明确定义的接口

	engine.NoRoute(func(ctx *gin.Context) {
		ctx.Writer.WriteHeader(http.StatusOK)
		_, _ = ctx.Writer.Write(static.IndexByte)
		ctx.Writer.Header().Add("Accept", "text/html")
		ctx.Writer.Flush()
	})
	rootGroup := engine.Group("")
	{
		rootGroup.GET("/health", func(c *gin.Context) {
			c.JSON(200, "ok")
		})
		rootGroup.Use(gzip.Gzip(gzip.DefaultCompression))
		setWebStatic(rootGroup)
	}
	//  /api/pn.jpg ==》 public/pn.jpg
	//
	routerGroup := engine.Group("/api/v1")
	setConf(initConf, routerGroup)
	///=== 路由// /api/akshdkahds
	nail.InitNailRouter(routerGroup)
	nail.InitToolRouter(routerGroup)
	logx.Debug("engine.Routes()", len(engine.Routes()))
	logx.Debug("server start:", "http://0.0.0.0:"+strconv.Itoa(initConf.Port))
	engine.Run(":" + strconv.Itoa(initConf.Port))
}

func setConf(conf conf.ServerConf, routerGroup *gin.RouterGroup) {
	if conf.Auth { //验证
		routerGroup.Use(middle.UserJwt())
		routerGroup.Use(middle.PermissionType())
	}
}

// mvc java
// 读取配置文件  --》 运行gin框架 --》router  <<- service  《—— repo 操作数据库 与 实体类
func setWebStatic(rootRouter *gin.RouterGroup) {
	rootRouter.StaticFS("/public", http.FS(static.Favicon))
	rootRouter.Use(func(c *gin.Context) {
		c.Next()
	})
	rootRouter.GET("/assets/*filepath", func(c *gin.Context) {
		c.Writer.Header().Set("Cache-Control", fmt.Sprintf("private, max-age=%d", 3600))
		staticServer := http.FileServer(http.FS(static.Assets))
		staticServer.ServeHTTP(c.Writer, c.Request)
	})
	rootRouter.GET("/", func(c *gin.Context) {
		staticServer := http.FileServer(http.FS(static.IndexHtml))
		staticServer.ServeHTTP(c.Writer, c.Request)
	})
}
